// 内部状态（可共享的数据）
interface BookIntrinsicState {
  title: string;
  author: string;
  isbn: string;
}

// 外部状态（不可共享的数据）
interface BookExtrinsicState {
  location: string;
  borrower: string;
  dueDate: string;
}

// 享元工厂
class BookFlyweightFactory {
  private static instance: BookFlyweightFactory;
  private flyweights: Map<string, BookIntrinsicState> = new Map();

  private constructor() {}

  static getInstance(): BookFlyweightFactory {
    if (!BookFlyweightFactory.instance) {
      BookFlyweightFactory.instance = new BookFlyweightFactory();
    }
    return BookFlyweightFactory.instance;
  }

  getFlyweight(isbn: string): BookIntrinsicState {
    if (!this.flyweights.has(isbn)) {
      // 这里模拟从数据库获取数据
      this.flyweights.set(isbn, {
        title: `Book ${isbn}`,
        author: `Author ${isbn}`,
        isbn: isbn
      });
    } else {
      console.log(isbn)
    }
    return this.flyweights.get(isbn)!;
  }

  getFlyweightCount(): number {
    return this.flyweights.size;
  }
}

// 享元对象
class BookFlyweight {
  constructor(
    private intrinsicState: BookIntrinsicState,
    private extrinsicState: BookExtrinsicState
  ) {}

  display(): string {
    return `
      Book: ${this.intrinsicState.title}
      Author: ${this.intrinsicState.author}
      ISBN: ${this.intrinsicState.isbn}
      Location: ${this.extrinsicState.location}
      Borrower: ${this.extrinsicState.borrower}
      Due Date: ${this.extrinsicState.dueDate}
    `;
  }
}

export { BookFlyweightFactory, BookFlyweight };
export type { BookIntrinsicState, BookExtrinsicState }; 